package com.heima.behavior.service.Imp;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryServiceImp implements ApBehaviorEntryService {
    /**
     * 根据用户id或者设备id生成collectionEntry
     * @param userId  用户id
     * @param equipmentId  设备id
     * @return
     */
        @Autowired
        MongoTemplate mongoTemplate;

        @Override
        public synchronized ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
            //1. 判断userId是否为空  不为空 使用userId查询  如果不存在基于userId创建实体数据
            if(userId != null){
                // 根据 type类型为用户关联  和  refId查询 是否有对应关联行为实体
                ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId)
                        .and("type").is(ApBehaviorEntry.Type.USER.getCode())), ApBehaviorEntry.class);

                // 如果行为实体为 null
                if(behaviorEntry == null){

                    // 创建对应行为实体
                    behaviorEntry = new ApBehaviorEntry();
                    behaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                    behaviorEntry.setRefId(userId);
                    behaviorEntry.setCreatedTime(new Date());
                    mongoTemplate.save(behaviorEntry);
                }
                return behaviorEntry;
            }
            //2. 判断设备id是否为空   不为空 使用设备id查询  如果不存在基于设备id创建实体数据
            if(equipmentId != null){
                // 根据 type类型为设备关联  和  refId查询 是否有对应关联行为实体
                ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(equipmentId)
                        .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())), ApBehaviorEntry.class);
                if(behaviorEntry == null){
                    behaviorEntry = new ApBehaviorEntry();
                    behaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                    behaviorEntry.setRefId(equipmentId);
                    behaviorEntry.setCreatedTime(new Date());
                    mongoTemplate.save(behaviorEntry);
                }
                return behaviorEntry;
            }
            return null;
    }
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult LikeOrCancel(LikesBehaviorDTO dto) {
         //1.创建ApBehaviorEntry中的信息
        ApBehaviorEntry behaviorEntry = creatBehaviorEntryMsg(dto);
        if (behaviorEntry.getType() != 1) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"未登录请先登录");
            log.info("未登录请先登录");
        }
        //2.点赞
            //根据当前用户id和查询实体类对象是否存在
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
            //不存在且行为是点赞 就新增 否则就是取消赞
            if (apLikesBehavior == null && dto.getOperation() == 0) {
                //覆盖不去创建
                apLikesBehavior = new ApLikesBehavior();
                apLikesBehavior.setEntryId(behaviorEntry.getId());
                apLikesBehavior.setArticleId(dto.getArticleId());
                apLikesBehavior.setCreatedTime(new Date());
                mongoTemplate.insert(apLikesBehavior);
            } else {
                //存在取消点赞 删除原先的值
                mongoTemplate.remove(query,ApLikesBehavior.class);
            }
        //System.out.println("===============================");
        NewBehaviorDTO mess = new NewBehaviorDTO();
            //对信息进行封装
        mess.setType(NewBehaviorDTO.BehaviorType.LIKES);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(dto.getOperation() == 0?1:-1);
        //使用rabbit发送消息
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("点赞行为 发送消息=={}",JSON.toJSONString(mess));
        //System.out.println("===============================");

        return ResponseResult.okResult();
    }

    /**
     * 获得基础信息并插入ApBehaviorEntry集合
     * @param likesBehaviorDTO
     * @return
     */
    private ApBehaviorEntry creatBehaviorEntryMsg(LikesBehaviorDTO likesBehaviorDTO) {
        //获得用户token中的id检查是否处于登陆状态
        ApUser user = AppThreadLocalUtils.getUser();
        //对数据进行判空
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户未携带ID或未携带设备ID");
        }
        //调用
        return  findByUserIdOrEquipmentId(user.getId(),likesBehaviorDTO.getEquipmentId());
    }
}
